package com.example.expresscheck.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.expresscheck.entity.Account;
import com.example.expresscheck.entity.Express;

public class AccountsDao {
	AccountsDBHelper dbHelper;

	public AccountsDao(Context context) {
		dbHelper = new AccountsDBHelper(context);

	}

	public void add(String account) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("insert into table_account (account) values (?)",
				new Object[] { account });
		db.close();
	}

	public void add(String account, String pswd) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("insert into table_account (account,pswd) values (?,?)",
				new Object[] { account, pswd });
		db.close();
	}

	public Account find(String account) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"select * from table_account where account=?",
				new String[] { account });
		if (cursor.moveToFirst()) {
			String pswd = cursor.getString(cursor.getColumnIndex("pswd"));
			db.close();
			return new Account(account, pswd);
		}
		db.close();
		return null;
	}

	public void delete(String account) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from table_account where account = ?",
				new Object[] { account });
		db.close();
	}

	public List<String> getListAccount() {
		List<String> list = new ArrayList<String>();
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from table_account", null);
		while (cursor.moveToNext()) {
			String account = cursor.getString(cursor.getColumnIndex("account"));
			list.add(account);
		}
		cursor.close();
		db.close();
		return list;
	}

	public void updatePswd(String account, String pswd) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL(
				"update table_account set pswd =?  where account = ?",
				new Object[] { pswd, account });
		db.close();
	}
}